package com.gzyj.flink.gps.map.beidoualarm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.gzyj.flink.driver.Driverlogininfo;
import com.gzyj.flink.dto.alarm.AlarmALLObject;
import com.gzyj.flink.dto.alarm.Kafka_VehicleNormalAlarm;
import com.gzyj.flink.dto.utils.ToolUtils;
import com.gzyj.flink.gps.GPSPosition;
import com.gzyj.flink.gps.config.RedisKeyPrefixConfig;
import com.gzyj.flink.gps.factory.RedisSessionFactory;
import com.gzyj.flink.gps.utils.IntUtils;
import com.gzyj.flink.utils.GpsIntUtils;
import com.gzyj.flink.utils.PointUtils;
import com.gzyj.flink.utils.RoadUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class BeidouZongDuanAlarm2KafkaVehicleNormalAlarmFun extends RichMapFunction<GPSPosition, Kafka_VehicleNormalAlarm> {


    private LettuceConnectionFactory factory;

    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory redisSessionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisSessionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


    @Override
    public void open(Configuration parameters) throws Exception {
        factory = RedisSessionFactory.getRedisFactory();
    }

    @Override
    public Kafka_VehicleNormalAlarm map(GPSPosition gpsPosition) throws Exception {
        RedisTemplate<String, Object> clusterRedisTemplate = getRedisTemplate(factory);
        Driverlogininfo driverLoginData = null;

        Object obj = clusterRedisTemplate.opsForValue().get(RedisKeyPrefixConfig.RedisKey_VehicleAlarm + gpsPosition.getVehId());
        Kafka_VehicleNormalAlarm vehicleNormalAlarm = null;
        if (obj == null) {
            vehicleNormalAlarm = new Kafka_VehicleNormalAlarm();
        } else {
            vehicleNormalAlarm = JSONObject.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect), Kafka_VehicleNormalAlarm.class);
        }

        obj = clusterRedisTemplate.opsForValue().get(RedisKeyPrefixConfig.RedisKey_DriverSignOn + gpsPosition.getVehId());

        if (obj == null) {
            driverLoginData = new Driverlogininfo();
        } else {
            driverLoginData = JSONObject.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect), Driverlogininfo.class);
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Kafka_VehicleNormalAlarm alarm = new Kafka_VehicleNormalAlarm();
        alarm.setVehicleId(gpsPosition.getVehId());
        alarm.setDeptId(gpsPosition.getDeptId());
        alarm.setNote(gpsPosition.getAlarmNoteExt());
        alarm.setVelocity(gpsPosition.getSpeedExt());
        alarm.setLimited(0);
        alarm.setLongitude(gpsPosition.getLngExt());
        alarm.setLatitude(gpsPosition.getLatExt());
        alarm.setElevation(Double.valueOf(gpsPosition.getALTITUDE()));
        alarm.setAngle(gpsPosition.getDIRECTION());
        alarm.setLocal(IntUtils.LocalExt(gpsPosition.getSTATUSBIT()) == 1);
        alarm.setAnalyzeModel(0);
        alarm.setCreateTime(sdf.format(new Date()));
        alarm.setUpdateTime(sdf.format(new Date()));
        alarm.setTime(gpsPosition.getTIME());
        alarm.setIsAlarm(true);
        alarm.setDriver(driverLoginData.getDriverName());
        alarm.setDriverNo(driverLoginData.getDriverNo());
        alarm.setQualificationCode(driverLoginData.getDriverNo());
        Map<String, String> yjcmAlarm = new HashMap<>();
        String alarmNote=gpsPosition.getAlarmNoteExt();


        String[] alarmtypes=new String[]{"超速报警","疲劳驾驶","紧急报警","GNSS模块发生故障","GNSS天线未接或被剪断","GNSS天线短路","终端主电源欠压","终端主电源掉电","终端LCD或显示器故障","TTS模块故障","摄像头故障","当天累计驾驶超时","超时停车","车辆油量异常","车辆被盗","车辆非法点火","车辆非法位移"};

        if ((vehicleNormalAlarm.getNote() != null && !vehicleNormalAlarm.getNote().equalsIgnoreCase(alarmNote))) {
            //不相等
            for (int i = 0; i < alarmtypes.length; i++) {
                String key=alarmtypes[i];

                String kw=key;

                if (!vehicleNormalAlarm.getNote().contains(key)
                        && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                        && gpsPosition.getAlarmNoteExt().contains(key))) {
                    //开始超速
                    AlarmALLObject cs = new AlarmALLObject();
                    cs.setBeginLon(gpsPosition.getLngExt());
                    cs.setBeginLat(gpsPosition.getLatExt());
                    cs.setBeginTime(gpsPosition.getGPSTimeExt());
                    cs.setBeginRoadName("未知道路");
                    cs.setBeginSpeed(gpsPosition.getSpeedExt());
                    cs.setMaxSpeed(gpsPosition.getSpeedExt());
                    cs.setDistance(0);
                    cs.setLon(gpsPosition.getLngExt());
                    cs.setLat(gpsPosition.getLatExt());
                    cs.setAlarmGuid(UUID.randomUUID().toString());

                    if (key.equalsIgnoreCase("疲劳驾驶")) kw="疲劳驾驶报警";
                    yjcmAlarm.put(kw, JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));

                } else if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                        && vehicleNormalAlarm.getNote().contains(key)
                        && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                        && gpsPosition.getAlarmNoteExt().contains(key))) {
                    if (key.equalsIgnoreCase("疲劳驾驶")) kw="疲劳驾驶报警";
                    Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), kw);

                    if (csobj != null) {

                        AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                        lastCsAlarm.setLat(gpsPosition.getLatExt());
                        lastCsAlarm.setLon(gpsPosition.getLngExt());
                        if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                            lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                        }
                        lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                        yjcmAlarm.put(kw, JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));


                    }

                }

            }


           /* if (!vehicleNormalAlarm.getNote().contains("超速报警")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("超速报警"))) {
                //开始超速
                AlarmALLObject cs = new AlarmALLObject();
                cs.setBeginLon(gpsPosition.getLngExt());
                cs.setBeginLat(gpsPosition.getLatExt());
                cs.setBeginTime(gpsPosition.getGPSTimeExt());
                cs.setBeginRoadName("未知道路");
                cs.setBeginSpeed(gpsPosition.getSpeedExt());
                cs.setMaxSpeed(gpsPosition.getSpeedExt());
                cs.setDistance(0);
                cs.setLon(gpsPosition.getLngExt());
                cs.setLat(gpsPosition.getLatExt());
                cs.setAlarmGuid(UUID.randomUUID().toString());

                yjcmAlarm.put("超速报警", JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));

            } else if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                    && vehicleNormalAlarm.getNote().contains("超速报警")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("超速报警"))) {

                Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), "超速报警");

                if (csobj != null) {

                    AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                    lastCsAlarm.setLat(gpsPosition.getLatExt());
                    lastCsAlarm.setLon(gpsPosition.getLngExt());
                    if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                        lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                    }
                    lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                    yjcmAlarm.put("超速报警", JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));


                }

            }

            if (!vehicleNormalAlarm.getNote().contains("疲劳驾驶")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("疲劳驾驶"))) {
                //开始超速
                AlarmALLObject cs = new AlarmALLObject();
                cs.setBeginLon(gpsPosition.getLngExt());
                cs.setBeginLat(gpsPosition.getLatExt());
                cs.setBeginTime(gpsPosition.getGPSTimeExt());
                cs.setBeginRoadName("未知道路");
                cs.setBeginSpeed(gpsPosition.getSpeedExt());
                cs.setMaxSpeed(gpsPosition.getSpeedExt());
                cs.setDistance(0);
                cs.setLon(gpsPosition.getLngExt());
                cs.setLat(gpsPosition.getLatExt());
                cs.setAlarmGuid(UUID.randomUUID().toString());

                yjcmAlarm.put("疲劳驾驶报警", JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));

            } else if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                    && vehicleNormalAlarm.getNote().contains("疲劳驾驶")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("疲劳驾驶"))) {

                Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), "疲劳驾驶报警");

                if (csobj != null) {

                    AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                    lastCsAlarm.setLat(gpsPosition.getLatExt());
                    lastCsAlarm.setLon(gpsPosition.getLngExt());
                    if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                        lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                    }
                    lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                    yjcmAlarm.put("疲劳驾驶报警", JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));


                }


            }*/


            clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_VehicleAlarm + gpsPosition.getVehId(), alarm, 8, TimeUnit.HOURS);


            if (!yjcmAlarm.isEmpty()) {
                clusterRedisTemplate.opsForHash().putAll(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), yjcmAlarm);
                clusterRedisTemplate.expire(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), 8, TimeUnit.HOURS);
            }

            return alarm;

        } else if ((vehicleNormalAlarm.getNote() != null && vehicleNormalAlarm.getNote().equalsIgnoreCase(alarmNote))) {
            //相等

            for (int i = 0; i < alarmtypes.length; i++) {
                String key=alarmtypes[i];

                String kw=key;

                if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                        && vehicleNormalAlarm.getNote().contains(key)
                        && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                        && gpsPosition.getAlarmNoteExt().contains(key))) {
                    if (key.equalsIgnoreCase("疲劳驾驶")) kw="疲劳驾驶报警";
                    Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), kw);

                    if (csobj != null) {

                        AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                        lastCsAlarm.setLat(gpsPosition.getLatExt());
                        lastCsAlarm.setLon(gpsPosition.getLngExt());
                        if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                            lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                        }
                        lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                        yjcmAlarm.put(kw, JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));


                    }else{
                        //开始超速
                        AlarmALLObject cs = new AlarmALLObject();
                        cs.setBeginLon(gpsPosition.getLngExt());
                        cs.setBeginLat(gpsPosition.getLatExt());
                        cs.setBeginTime(gpsPosition.getGPSTimeExt());
                        cs.setBeginRoadName("未知道路");
                        cs.setBeginSpeed(gpsPosition.getSpeedExt());
                        cs.setMaxSpeed(gpsPosition.getSpeedExt());
                        cs.setDistance(0);
                        cs.setLon(gpsPosition.getLngExt());
                        cs.setLat(gpsPosition.getLatExt());
                        cs.setAlarmGuid(UUID.randomUUID().toString());
                        yjcmAlarm.put(kw, JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));
                    }


                }

            }

           /* if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                    && vehicleNormalAlarm.getNote().contains("超速报警")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("超速报警"))) {

                Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), "超速报警");

                if (csobj != null) {

                    AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                    lastCsAlarm.setLat(gpsPosition.getLatExt());
                    lastCsAlarm.setLon(gpsPosition.getLngExt());
                    if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                        lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                    }
                    lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                    yjcmAlarm.put("超速报警", JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));
                }else{
                    AlarmALLObject cs = new AlarmALLObject();
                    cs.setBeginLon(gpsPosition.getLngExt());
                    cs.setBeginLat(gpsPosition.getLatExt());
                    cs.setBeginTime(gpsPosition.getGPSTimeExt());
                    cs.setBeginRoadName("未知道路");
                    cs.setBeginSpeed(gpsPosition.getSpeedExt());
                    cs.setMaxSpeed(gpsPosition.getSpeedExt());
                    cs.setDistance(0);
                    cs.setLon(gpsPosition.getLngExt());
                    cs.setLat(gpsPosition.getLatExt());
                    cs.setAlarmGuid(UUID.randomUUID().toString());
                    yjcmAlarm.put("超速报警", JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));
                }

            }

            if (StringUtils.isNotEmpty(vehicleNormalAlarm.getNote())
                    && vehicleNormalAlarm.getNote().contains("疲劳驾驶")
                    && (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())
                    && gpsPosition.getAlarmNoteExt().contains("疲劳驾驶"))) {

                Object csobj = clusterRedisTemplate.opsForHash().get(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), "疲劳驾驶报警");

                if (csobj != null) {

                    AlarmALLObject lastCsAlarm = JSONObject.parseObject(String.valueOf(csobj), AlarmALLObject.class);

                    lastCsAlarm.setLat(gpsPosition.getLatExt());
                    lastCsAlarm.setLon(gpsPosition.getLngExt());
                    if (gpsPosition.getSpeedExt() >= lastCsAlarm.getMaxSpeed()) {
                        lastCsAlarm.setMaxSpeed(gpsPosition.getSpeedExt());
                    }
                    lastCsAlarm.setDistance(ToolUtils.GetDistance(gpsPosition.getLngExt(),gpsPosition.getLatExt(),lastCsAlarm.getBeginLon(),lastCsAlarm.getBeginLat()));

                    yjcmAlarm.put("疲劳驾驶报警", JSON.toJSONString(lastCsAlarm, SerializerFeature.DisableCircularReferenceDetect));


                }else{
                    //开始超速
                    AlarmALLObject cs = new AlarmALLObject();
                    cs.setBeginLon(gpsPosition.getLngExt());
                    cs.setBeginLat(gpsPosition.getLatExt());
                    cs.setBeginTime(gpsPosition.getGPSTimeExt());
                    cs.setBeginRoadName("未知道路");
                    cs.setBeginSpeed(gpsPosition.getSpeedExt());
                    cs.setMaxSpeed(gpsPosition.getSpeedExt());
                    cs.setDistance(0);
                    cs.setLon(gpsPosition.getLngExt());
                    cs.setLat(gpsPosition.getLatExt());
                    cs.setAlarmGuid(UUID.randomUUID().toString());
                    yjcmAlarm.put("疲劳驾驶报警", JSON.toJSONString(cs, SerializerFeature.DisableCircularReferenceDetect));
                }


            }*/


            clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_VehicleAlarm + gpsPosition.getVehId(), alarm, 8, TimeUnit.HOURS);


            if (!yjcmAlarm.isEmpty()) {
                clusterRedisTemplate.opsForHash().putAll(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), yjcmAlarm);
                clusterRedisTemplate.expire(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), 8, TimeUnit.HOURS);
            }
            return alarm;

        } else if (StringUtils.isNotEmpty(gpsPosition.getAlarmNoteExt())&&StringUtils.isEmpty(vehicleNormalAlarm.getNote())) {
            clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_VehicleAlarm + gpsPosition.getVehId(), alarm, 8, TimeUnit.HOURS);


            if (!yjcmAlarm.isEmpty()) {
                clusterRedisTemplate.opsForHash().putAll(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), yjcmAlarm);
                clusterRedisTemplate.expire(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), 8, TimeUnit.HOURS);
            }
            return alarm;
        }

        clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_VehicleAlarm + gpsPosition.getVehId(), alarm, 8, TimeUnit.HOURS);


        if (!yjcmAlarm.isEmpty()) {
            clusterRedisTemplate.opsForHash().putAll(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), yjcmAlarm);
            clusterRedisTemplate.expire(RedisKeyPrefixConfig.RedisKey_CmAlarm + gpsPosition.getVehId(), 8, TimeUnit.HOURS);
        }

        return null;
    }
}
